package com.yilin.platform.base_core.interceptor;

import com.yilin.platform.base_core.application.BaseCode;
import com.yilin.platform.base_core.commons.annotation.Explain;
import com.yilin.platform.base_core.commons.annotation.NotNull;
import com.yilin.platform.base_core.commons.utils.FieldUtil;
import com.yilin.platform.base_core.commons.utils.JsonUtil;
import com.yilin.platform.base_core.commons.utils.constant.HttpConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求参数验证拦截器
 *
 * @author zhangjinyuan
 * @date 2022/11/7
 */
public class ParamInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(ParamInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        if (!(handler instanceof HandlerMethod)){
            responseErr( response,  BaseCode.RES_NOT_EXIST, "请求的链接地址不存在");
            return false;
        }
        /// 用户类型拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        NotNull methodAnnotation = handlerMethod.getMethodAnnotation(NotNull.class);
        if (methodAnnotation == null) return true;
//        List<Field> parametersField = getParametersFields(handlerMethod.getMethodParameters());
//        here:
//        for (String annotationValue : methodAnnotation.value()) {
//            for (MethodParameter methodParameter : handlerMethod.getMethodParameters()) {
//                Class<?> aClass = methodParameter.getParameterType();
//                if (!aClass.getName().contains("com.yilin.platform.entity") && annotationValue
//                        .equals(methodParameter.getParameterName())) {
//                    String parameter = request.getParameter(annotationValue);
//                    if (parameter == null || ParamUtil.isNull(aClass, parameter)) {
//                        String message = getMessage(methodParameter.getParameterAnnotation(Explain.class),
//                                methodParameter, null);
//                        String sysWarning = "⚠⚠⚠⚠警告！客户[IP：%s]，请求方法：%s，请求参数[%s]为空！";
//                        logger.warn(String.format(sysWarning, AppUtil.getIp(request),
//                                handlerMethod.getMethod().getName(), message));
//                        responseErr(response, BaseCode.FAIL_CODE, message + "为空");
//                        return false;
//                    }
//                    continue here;
//                }
//            }
//            for (Field declaredField : parametersField) {
//                if (declaredField.getName().equals(annotationValue)) {
//                    String parameter = request.getParameter(annotationValue);
//                    if (parameter == null || ParamUtil.isNull(declaredField.getType(), parameter)) {
//                        String message = getMessage(declaredField.getAnnotation(Explain.class),
//                                null, declaredField);
//                        String sysWarning = "⚠⚠⚠⚠警告！客户[IP：%s]，请求方法：%s，请求参数[%s]为空！";
//                        logger.warn(String.format(sysWarning, AppUtil.getIp(request),
//                                handlerMethod.getMethod().getName(), message));
//                        responseErr(response, BaseCode.FAIL_CODE, message + "为空");
//                        return false;
//                    }
//                    continue here;
//                }
//            }
//        }
        return true;
    }

    //返回前台数据
    private void responseErr(HttpServletResponse response, Integer code, String msg) {
        try {
            Map<String, Object> returnData = new HashMap<>();
            response.setContentType("application/json");//设置格式为text/json 
            response.setCharacterEncoding("UTF-8");//设置字符集为'UTF-8'
            returnData.put(HttpConstant.SUCCESS, false);
            returnData.put(HttpConstant.CODE, code);
            returnData.put(HttpConstant.MSG, msg);
            PrintWriter write = response.getWriter();
            write.write(JsonUtil.objectToJson(returnData));
            write.flush();
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<Field> getParametersFields(MethodParameter[] methodParameters) {
        List<Field> declaredFields = new ArrayList<>();
        for (MethodParameter methodParameter : methodParameters) {
            Class<?> aClass = methodParameter.getParameterType();
            if (aClass.getName().contains("com.yilin.tms.core.entity") && !aClass.isEnum()) {
                List<Field> fields = FieldUtil.getFields(aClass);
                declaredFields.addAll(fields);
            }
        }
        return declaredFields;
    }

    private String getMessage(Explain annotation, MethodParameter methodParameter, Field declaredField) {
        String message = "";
        if (annotation != null) message = annotation.value();
        else if (methodParameter != null) message = methodParameter.getParameterName();
        else if (declaredField != null) message = declaredField.getName();
        return message;
    }
}
